package com.bawei.module_base.ui.base

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider


abstract class BaseActivity<VM : ViewModel,DBD: ViewDataBinding> :AppCompatActivity(){

    protected  lateinit var binding:DBD
    protected lateinit var viewModel:VM


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //先加载布局
        if (getLayout()==0){
            throw NotImplementedError("错误：未实现getLayout()方法！")
        }
        //绑定DataBinding
        binding=DataBindingUtil.setContentView(this,getLayout())
        //lifecycle监听
        binding.lifecycleOwner=this

        //创建 viewModel 实例
        viewModel= ViewModelProvider(this)[getViewModelClass()]
        initData()

    }
    abstract fun getLayout():Int
    abstract fun initData()

    // 获取 ViewModel 的类
    abstract fun getViewModelClass():Class<VM>

    override fun onDestroy() {
        super.onDestroy()
        if (binding!=null){
            binding.unbind()
        }
    }
}